<script lang='ts' setup>
import { reactive, ref } from 'vue' 
import type { FormInstance, FormRules } from 'element-plus' 
import {dirAdd } from '/@/api/commodity';


const emit = defineEmits(['refresh']);
const ruleFormRef = ref<FormInstance>()
const state = reactive({
    type:'',
    dialog:{
        title:'',
        isShowDialog:false,
        loading:false,
    },
})

const ruleForm = reactive({ 
    id: null,
	name: '',
})

const rules = reactive<FormRules<any>>({
	name: [{ required: true, message: '请输入目录名称', trigger: 'blur' }], 
})

const submitForm =  (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate( async (valid, fields) => {
		if (valid) {
            let params = {
                id: ruleForm.id,
                name: ruleForm.name,
                group: ruleForm.name,
            }
            const { results } = await dirAdd(params);
            emit('refresh');
            closeDialog()
		} else {
			console.log('error submit!', fields)
		}
	})
}

const openDialog = ( type: string, data? : any) => {
    ruleForm.name = '';
    state.type = type;
    if(type == 'add'){
        state.dialog.title = '新增'

    }else if(type == 'edit'){
        state.dialog.title = '编辑';
        ruleForm.id = null;
        ruleForm.name = '';
    }
    state.dialog.isShowDialog = true
}

const closeDialog = () => {
    state.dialog.isShowDialog = false
}

// 暴露变量
defineExpose({
	openDialog
});

</script>
<template>
    <main>
        <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog"  center class="borderRadius10" width="490">
            <section>
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
                    <el-form-item label="分类名称：" prop="name">
                        <el-input v-model="ruleForm.name" placeholder="请输入分类名称" />
                    </el-form-item>
                </el-form>
                <el-row justify="end" class="mt20">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                </el-row>
            </section>
        </el-dialog>
    </main>
</template>

<style lang='scss' scoped>
</style>